package com.h2cloud.aspect.cacheAble;

import com.h2cloud.aspect.BaseAspect;
import com.h2cloud.depends.cache.CacheService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

/***
 * 清理缓存拦截器
 */
@Order(4)
//@Aspect
//@Component
public class CacheableEvictAspect extends BaseAspect {

    private final static Logger logger = LoggerFactory.getLogger(CacheableEvictAspect.class);

    @Autowired
    private CacheService cacheService;

    /**
     * 后期改成配置
     */
    private static boolean isCacheEnabled = true;

    @Pointcut("@annotation(com.h2cloud.aspect.cacheAble.CacheableEvict)")
    public void methodPointCut() {

    }

    /**
     *
     */
    @AfterReturning("methodPointCut()")
    public void doAround(JoinPoint joinPoint) {
        CacheableEvict cacheable = getAnnotation(joinPoint, CacheableEvict.class);
        if (cacheable != null && isCacheEnabled) {
            Object[] arguments = joinPoint.getArgs();

            arguments = CacheAspect.getArgStr(arguments, cacheable.paramName(), joinPoint.getSignature());

//		String targetName = cacheable.targetClassName();
//		String methodName = cacheable.targetMethodName();
//		String key = getCacheKey(cacheable.key(),targetName, methodName, arguments);

            String key = getCacheKey(cacheable.key(), arguments);
            cacheService.remove(key);
            logger.debug("cache was removed, cacheKey:{}", key);
        }
    }

}
